package com.generation.builder;

import com.generation.Bean.Constants;
import com.generation.Bean.FieldInfo;
import com.generation.Bean.TableInfo;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author mockingjay
 * @date 2023/4/16 - 17:24
 */
public class BuildMapperXml {
    private static final Logger LOGGER = LoggerFactory.getLogger(BuildrPoJo.class);

    public static void excute(TableInfo tableInfo) {
        File folder = new File(Constants.PATH_MAPPER_XML);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String className = tableInfo.getBeanName() + Constants.SUFFIX_MAPPER;
        File poFile = new File(folder, className + ".xml");

        OutputStream out = null;
        OutputStreamWriter ow = null;
        BufferedWriter bw = null;
        String classPo=tableInfo.getBeanName();
        try {
            out = new FileOutputStream(poFile);
            ow = new OutputStreamWriter(out, "utf8");
            bw = new BufferedWriter(ow);
            //配置velocity资源加载器
            Properties prop = new Properties();
            prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            Velocity.init(prop);
            //封装mapper模板数据
            Map<String,Object> mapperXmlTemplateData=Constants.TEMPLATE_MAPPER_XML_DATA;
            List<FieldInfo> columns=tableInfo.getFieldInfoList();
            mapperXmlTemplateData.put("columns",columns);
            mapperXmlTemplateData.put("className",classPo);

            VelocityContext context = new VelocityContext(mapperXmlTemplateData);
            String templatePath=Constants.TEMPLATE_MAPPER_XML;
            Template tpl = Velocity.getTemplate(templatePath, "UTF-8");
            tpl.merge(context, bw);

        } catch (Exception e) {
            LOGGER.error("创建mapper xml失败", e);
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ow != null) {
                try {
                    ow.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
